package com.example.print.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.example.print.R;
import com.example.print.fragment.PrintCodeFragment;
import com.example.print.fragment.PrintPictureFragment;
import com.example.print.fragment.PrintTemplateFragment;
import com.example.print.fragment.PrintTextFragment;
import com.google.android.material.tabs.TabLayout;
import com.panling.printapi.Printer;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private String TAG = "MainActivity";

    private Context context;
    private static String version = "";
    private AlertDialog mAlertDialog = null;
    private View mView;
    public Printer mPrinter;

    private TabLayout mTab;
    private ViewPager mViewPager;
    private DrawerLayout mDrawerLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);

        context = this;
        initView();
        initActionBar();
        initViewPager();

        mView = View.inflate(getApplicationContext(), R.layout.dialog_layout, null);
        mAlertDialog = new AlertDialog.Builder(this)
                .setView(mView)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        mAlertDialog.cancel();
                    }
                }).create();

        mAlertDialog.setTitle(getString(R.string.PrintVersion));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu_setting, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.version) {
            if (TextUtils.isEmpty(version)) {
                mHandler.sendEmptyMessage(2);
            }
            Log.d(TAG, "getVersion...." + version);
            showPopup();
            //mPrinter.free();//he jiang for test
            return true;
        }
        if (item.getItemId() == R.id.upgradeMcu) {
            Toast.makeText(context, "暂不开放！", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (item.getItemId() == R.id.upgradeFont) {
            Toast.makeText(context, "暂不开放！", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (item.getItemId() == R.id.Restore) {
            mHandler.sendEmptyMessage(3);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            int what = msg.what;
            if (what == 0) {    //update
                TextView tv = (TextView) mAlertDialog.findViewById(R.id.tv_dialog);
                if (TextUtils.isEmpty(version)) {
                    tv.setText("版本信息还没写");
                    version = mPrinter.getVersion();
                } else {
                    tv.setText(" " + version);
                }
                Log.e(TAG, "showPopup.mHandler.....2." + mAlertDialog.isShowing() + "," + getClass());
                if (!mAlertDialog.isShowing()) {
                    mAlertDialog.show();
                }
            } else if (what == 1) {
                mAlertDialog.cancel();
            } else if (what == 2) {
                version = mPrinter.getVersion();
            } else if (what == 3) {
                mPrinter.restoreDefault();
                //mPrinter.Restore_factory(0);
                Toast.makeText(context, "恢复出厂成功！", Toast.LENGTH_SHORT).show();
            }
        }
    };

    /**
     * 获取版本信息功能
     */
    private void showPopup() {
        Log.e(TAG, "showPopup.....1." + mAlertDialog.isShowing() + "," + getClass());
        mAlertDialog.show();
        Log.e(TAG, "showPopup.....2." + mAlertDialog.isShowing() + "," + getClass());
        mHandler.sendEmptyMessage(0);
    }

    private void initViewPager() {
        MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getSupportFragmentManager());

        List<Fragment> list = new ArrayList<>();
        list.add(new PrintTextFragment());
        list.add(new PrintCodeFragment());
        list.add(new PrintPictureFragment());
        list.add(new PrintTemplateFragment());

        adapter.setFragmentList(list);
        mTab.addTab(mTab.newTab());
        mTab.addTab(mTab.newTab());
        mTab.addTab(mTab.newTab());
        mTab.addTab(mTab.newTab());
        mViewPager.setAdapter(adapter);

        mTab.getTabAt(0).setText(R.string.TextPrint);
        mTab.getTabAt(1).setText(R.string.CodePrint);
        mTab.getTabAt(2).setText(R.string.PicturePrint);
        mTab.getTabAt(3).setText(R.string.TemplatePrint);
    }

    private void initActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    private void initView() {
        mTab = (TabLayout) findViewById(R.id.tab);
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mTab.setupWithViewPager(mViewPager);
    }

    @Override
    public void onResume() {
        super.onResume();

        try {
            mPrinter = Printer.getInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        new InitTask().execute();
        Log.e(TAG, "hejiang-onResume......" + getClass());

        if (TextUtils.isEmpty(version)) {
            mHandler.sendEmptyMessageDelayed(2, 2 * 1000);
        }

        mPrinter.setPrinterStatusCallBack(new CallBack());
    }

    @Override
    public void onStop() {
        super.onStop();

        Log.d(TAG, "onStop..free .start." + getClass());
        if (mPrinter != null) {
            mPrinter.free();
        }
        Log.d(TAG, "onStop..free .end." + getClass());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            Log.e(TAG, "onKeyDown-....KEYCODE_BACK=BACK" + "," + getClass());
            if (mPrinter != null) {
                mPrinter.free();
            }
            finish();
            //System.exit(0);
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    protected class InitTask extends AsyncTask<String, Integer, Boolean> {
        ProgressDialog mypDialog;

        @Override
        protected Boolean doInBackground(String... params) {
            // TODO Auto-generated method stub
            return mPrinter.init();
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            mypDialog.cancel();
            if (!result) {
                Toast.makeText(context, "init fail", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "init success", Toast.LENGTH_SHORT).show();
                mPrinter.open(false);
                initParameter();
            }
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            mypDialog = new ProgressDialog(context);
            mypDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mypDialog.setMessage("init Printer...");
            mypDialog.setCanceledOnTouchOutside(false);
            mypDialog.show();
        }
    }

    private int speed = 200;
    private void initParameter(){
        mPrinter.setFlowcontrol(1);
        mPrinter.setPrintSpeed(speed);
    }

    private boolean isNORMAL = true;//打印机是否正常
    //private Printer.PrinterStatusCallBack msgCallBack = null;
    private class CallBack implements Printer.PrinterStatusCallBack {
        @Override
        public void message(Printer.PrinterStatus infoCode) {
            Log.e(TAG, "Thread CallBack...infoCode=" + infoCode);
            switch (infoCode) {
                case NORMAL://正常:
                case LEISURE:
                    isNORMAL = true;
                    setTitle(getString(R.string.app_name) + "--正常--");
                    break;
                case UNLEISURED://打印机繁忙
                    isNORMAL = false;
                    setTitle(getString(R.string.app_name) + "--繁忙--");
                    break;
                case LACKOFPAPER://缺纸
                    isNORMAL = false;
                    setTitle(getString(R.string.app_name) + "--" + getString(R.string.lackofpaper) + "--");
                    break;
            }
        }
    }

    public boolean GetPrinterStatus(){
        return isNORMAL;
    }

}